package com.acceptable.qucun.generic.filter;

import com.acceptable.qucun.generic.util.result.ResultUtil;
import com.acceptable.qucun.generic.util.result.error.BaseErrorResult;
import com.acceptable.qucun.generic.util.result.error.GenericErrorResult;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.AccessDeniedException;

public class EncodingFilter implements Filter {
    private String encoding = "UTF-8";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        try {
            chain.doFilter(request, response);
        } catch (AccessDeniedException e){
            response.getWriter().write(ResultUtil.error(GenericErrorResult.ACCESS_DENIED_ERROR));
        } catch (Exception e){
            e.printStackTrace();
            BaseErrorResult result = ResultUtil.getErrorResultFromAll(e.getMessage());
            if(result != null)
                response.getWriter().write(ResultUtil.error(result));
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
    }
}
